package softswitch.agi;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.ejb.Stateless;
import org.asteriskjava.fastagi.AgiChannel;
import org.asteriskjava.fastagi.AgiException;
import org.asteriskjava.fastagi.AgiRequest;
import org.asteriskjava.fastagi.BaseAgiScript;


@Stateless
public class Password extends BaseAgiScript {
	
	
	public void service(AgiRequest request, AgiChannel channel) throws AgiException {


		answer();
		
		
		try{
			Class.forName("org.postgresql.Driver");
			
		}
		catch(ClassNotFoundException e){
			System.out.println("E1");
		}
		
		Connection con = null;
		
		try{
			con = DriverManager.getConnection("jdbc:postgresql://192.168.14.4:5432/asterisk360","postgres","postgres");
		}
		catch(SQLException e){
			e.printStackTrace();
			System.out.println("Error Connect");
		}
		
		if(con != null){
			try {
				String actual = getData("password/welcome",10000,6);
				String sql = "SELECT COUNT(*) FROM softswitch.circuit WHERE code = "+ actual+ " ; ";
				Statement stmt = con.createStatement();
				
				ResultSet rs = stmt.executeQuery(sql);
				rs.next();
				Integer out = rs.getInt(1);
				if(out==0){
					exec("Playback","password/incorrecto");
					hangup();
				}
				else{
					String nueva = getData("password/password",10000,6);
					String nuevaagain = getData("password/passwordagain",10000,6);
					
					if(nueva.equals(nuevaagain)){
						
						String sql2 = "UPDATE softswitch.circuit SET code = "+ nueva + " WHERE code = "+ actual+ " ; ";
						Statement stmt2 = con.createStatement();
						stmt2.executeUpdate(sql2);						
						exec("Playback","password/sucessfull");
					}
					else{
						exec("Playback","password/passworddontmatch");
						hangup();
					}
					
					
				}
				
				
				
				
				
				con.close();
			}
			catch (SQLException e) {
				System.out.println("EXCECUTE QUERY");
				e.printStackTrace();
			}
		}
		
		
		
	}//service()
	
			
	

	
}// Class
